<template>
    <div class="patient-chart-container">
        <div class="report-header">
            <h2>护士巡查打卡报表</h2>
            <div class="report-controls">
                <div class="report-period">
                    <el-button :type="reportType === 'week' ? 'primary' : ''"
                        @click="setReportType('week')">周报</el-button>
                    <el-button :type="reportType === 'month' ? 'primary' : ''"
                        @click="setReportType('month')">月报</el-button>
                </div>
                <div class="date-picker">
                    <el-date-picker v-model="dateRange" type="daterange" range-separator=" - " start-placeholder="开始日期"
                        end-placeholder="结束日期" :disabled-date="disabledDate" @change="handleDateChange" />
                </div>
               
                <div class="export-buttons">
                    <el-button type="success" size="small" @click="exportData">
                        <el-icon>
                            <Download />
                        </el-icon> 导出数据
                    </el-button>
                    <el-button type="primary" size="small" @click="refreshData">
                        <el-icon>
                            <Refresh />
                        </el-icon> 刷新
                    </el-button>
                </div>
            </div>
        </div>
        <div v-loading="loading" class="chart-container">
            <div v-if="error" class="error-message">
                <el-alert title="加载数据失败" type="error" :description="error" show-icon />
                <el-button class="retry-button" type="primary" size="small" @click="fetchData">重试</el-button>
            </div>
            <div v-else-if="!hasData" class="no-data-message">
                <el-empty description="暂无数据" />
            </div>
            <div v-else ref="chartContainer" class="chart-wrapper"></div>
        </div>


    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, computed } from 'vue';
import * as echarts from 'echarts';
import { useRoute } from 'vue-router';
import { Download, Refresh } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import http from '@/api/http.js';

// 图表容器引用
const chartContainer = ref<HTMLElement | null>(null);
let chart: echarts.ECharts | null = null;

// 报表类型：周报或月报
const reportType = ref('week');

// 日期范围
const dateRange = ref([
    new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000),
    new Date()
]);

// 加载状态和错误信息
const loading = ref(false);
const error = ref('');

// 限制日期选择范围 - 不能选择未来日期
const disabledDate = (time: Date) => {
    return time.getTime() > Date.now();
};

// 护士巡查数据
const patrolData = reactive({
    nurseNames: [] as string[],
    totalTasks: [] as number[],
    completedTasks: [] as number[],
    rates: [] as number[]
});

// 计算属性: 是否有数据
const hasData = computed(() => {
    return patrolData.nurseNames.length > 0;
});

// 新增的响应式变量
const sortBy = ref('totalTasks');
const searchQuery = ref('');
const filteredData = computed(() => {
    let data = patrolData.nurseNames.map((name, index) => ({
        name,
        totalTasks: patrolData.totalTasks[index],
        completedTasks: patrolData.completedTasks[index],
        rates: patrolData.rates[index]
    }));

    // 搜索过滤
    if (searchQuery.value) {
        data = data.filter(item =>
            item.name.toLowerCase().includes(searchQuery.value.toLowerCase())
        );
    }

    // 排序
    data.sort((a, b) => {
        if (sortBy.value === 'rates') {
            return b.rates - a.rates;
        } else if (sortBy.value === 'completedTasks') {
            return b.completedTasks - a.completedTasks;
        } else {
            return b.totalTasks - a.totalTasks;
        }
    });

    return data;
});



// 设置报表类型
const setReportType = (type: 'week' | 'month') => {
    reportType.value = type;

    // 根据报表类型调整日期范围
    const endDate = new Date();
    let startDate;

    if (type === 'week') {
        startDate = new Date(endDate.getTime() - 7 * 24 * 60 * 60 * 1000);
    } else {
        startDate = new Date(endDate);
        startDate.setDate(1);
    }

    dateRange.value = [startDate, endDate];
    fetchData();
};

// 处理日期变更
const handleDateChange = () => {
    fetchData();
};

// 加载数据
const fetchData = async () => {
    if (!dateRange.value || !dateRange.value[0] || !dateRange.value[1]) return;

    const startDate = formatDate(dateRange.value[0]);
    const endDate = formatDate(dateRange.value[1]);

    loading.value = true;
    error.value = '';

    try {
        // 使用模拟数据 - 实际项目中应该替换为真实的API调用
        // 示例: const res = await http.get(`/api/NursePatrol/GetPatrolReport?startDate=${startDate}&endDate=${endDate}`);

        // 模拟后端请求延迟
        await new Promise(resolve => setTimeout(resolve, 800));

        const mockData = generateMockData();
        patrolData.nurseNames = mockData.nurseNames;
        patrolData.totalTasks = mockData.totalTasks;
        patrolData.completedTasks = mockData.completedTasks;
        patrolData.rates = mockData.rates;

        // 清除任何旧错误
        error.value = '';

        // 在下一个 tick 渲染图表 (确保 DOM 已更新)
        setTimeout(() => {
            renderChart();
        }, 0);

    } catch (err) {
        console.error('获取巡查数据失败:', err);
        error.value = err instanceof Error ? err.message : '加载数据时发生错误';
    } finally {
        loading.value = false;
    }
};

// 日期格式化
const formatDate = (date: Date): string => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
};

// 生成模拟数据 - 使用图片中的数据
const generateMockData = () => {
    return {
        nurseNames: ['胡素敏', '李晓晓', '刘菲敏', '王璐', '谢依凌', '蒋媛', '周丽芬', '朱倩倩', '唐妃'],
        totalTasks: [60, 80, 75, 74, 88, 82, 80, 90, 92],
        completedTasks: [54, 76, 69, 72, 85, 82, 79, 82, 86],
        rates: [90, 95, 98, 99, 94, 99, 92, 93, 89]
    };
};

// 导出数据
const exportData = () => {
    if (!hasData.value) {
        ElMessage.warning('当前没有数据可导出');
        return;
    }

    // 创建CSV内容
    let csvContent = '护士姓名,总巡查任务数 (次),实际打卡数 (次),准点率 (%)\n';

    for (let i = 0; i < patrolData.nurseNames.length; i++) {
        csvContent += `${patrolData.nurseNames[i]},${patrolData.totalTasks[i]},${patrolData.completedTasks[i]},${patrolData.rates[i]}\n`;
    }

    // 创建Blob对象并下载
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');

    const startDate = formatDate(dateRange.value[0]);
    const endDate = formatDate(dateRange.value[1]);
    const reportTypeName = reportType.value === 'week' ? '周报' : '月报';

    link.setAttribute('href', url);
    link.setAttribute('download', `护士巡查${reportTypeName}_${startDate}_${endDate}.csv`);
    link.style.visibility = 'hidden';

    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    ElMessage.success('数据导出成功');
};

// 刷新数据
const refreshData = () => {
    fetchData();
    ElMessage.success('数据已刷新');
};

// 处理排序
const handleSort = () => {
    // 排序逻辑已通过计算属性实现
};

// 处理搜索
const handleSearch = () => {
    // 搜索逻辑已通过计算属性实现
};

// 渲染图表
const renderChart = () => {
    if (!chartContainer.value) return;

    if (!chart) {
        chart = echarts.init(chartContainer.value);
    }

    const option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: function (params: any) {
                const totalTasks = params[0].value;
                const completedTasks = params[1].value;
                const rate = params[2].value;

                return `${params[0].name}<br />
                总巡查任务数: ${totalTasks} 次<br />
                实际打卡数: ${completedTasks} 次<br />
                准点率: ${rate}%`;
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                data: filteredData.value.map(item => item.name),
                axisTick: {
                    alignWithLabel: true
                },
                axisLabel: {
                    rotate: filteredData.value.length > 10 ? 45 : 0,
                    interval: 0
                }
            }
        ],
        yAxis: [
            {
                type: 'value',
                name: '',
                min: 0,
                max: 100,
                position: 'left',
                axisLine: {
                    show: true
                },
                axisLabel: {
                    formatter: '{value}'
                }
            }
        ],
        series: [
            {
                name: '总巡查任务数',
                type: 'bar',
                barWidth: '20%',
                data: filteredData.value.map(item => item.totalTasks),
                itemStyle: {
                    color: '#409EFF'
                },
                label: {
                    show: true,
                    position: 'top',
                    color: '#409EFF'
                }
            },
            {
                name: '实际打卡数',
                type: 'bar',
                barWidth: '20%',
                data: filteredData.value.map(item => item.completedTasks),
                itemStyle: {
                    color: '#FFA500'
                },
                label: {
                    show: true,
                    position: 'top',
                    color: '#FFA500'
                }
            },
            {
                name: '准点率',
                type: 'bar',
                barWidth: '20%',
                data: filteredData.value.map(item => item.rates),
                itemStyle: {
                    color: '#67C23A'
                },
                label: {
                    show: true,
                    position: 'top',
                    color: '#67C23A',
                    formatter: '{c}%'
                }
            }
        ]
    };

    chart.setOption(option);
};

// 处理窗口大小调整
const handleResize = () => {
    if (chart) {
        chart.resize();
    }
};

// 窗口大小改变时调整图表大小
window.addEventListener('resize', handleResize);

onMounted(() => {
    fetchData();
});

// 监听日期变化
watch(dateRange, () => {
    fetchData();
});
</script>

<style scoped>
.patient-chart-container {
    width: 100%;
    padding: 20px;
    background-color: #fff;
}

.report-header {
    display: flex;
    flex-direction: column;
    gap: 15px;
    margin-bottom: 20px;
    border-bottom: 1px solid #ebeef5;
    padding-bottom: 15px;
}

.statistics-cards {
    margin-bottom: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-value {
    font-size: 24px;
    font-weight: bold;
    color: #303133;
    text-align: center;
}

.filter-controls {
    display: flex;
    gap: 10px;
}

.data-table {
    margin-top: 20px;
}

@media (min-width: 768px) {
    .report-header {
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
    }
}

.report-header h2 {
    margin: 0;
    font-size: 18px;
    font-weight: 500;
    color: #303133;
}

.report-controls {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
}

.chart-container {
    width: 100%;
    height: 400px;
    margin-top: 20px;
    position: relative;
}

.chart-wrapper {
    width: 100%;
    height: 100%;
}

.chart-legend {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 20px;
    margin-top: 10px;
}

.legend-item {
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #606266;
}

.legend-color {
    width: 16px;
    height: 16px;
    margin-right: 8px;
    border-radius: 2px;
}

.error-message,
.no-data-message {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100%;
}

.retry-button {
    margin-top: 20px;
}

.export-buttons {
    display: flex;
    gap: 10px;
}

@media (max-width: 767px) {
    .report-controls {
        width: 100%;
    }

    .date-picker {
        width: 100%;
    }

    .date-picker :deep(.el-date-editor) {
        width: 100% !important;
    }

    .filter-controls {
        width: 100%;
    }

    .filter-controls .el-select,
    .filter-controls .el-input {
        width: 100%;
    }
}
</style>